//圆形按钮图标
var semicircleButtons = document.querySelectorAll(".round,.buttons-group button[icon]")
//icon 图标插入
for (let button of semicircleButtons) {
	var iconSrc = button.getAttribute("icon")
	var iconAfterSrc = button.getAttribute("after-icon")
	if (iconSrc != null) {
		button.innerHTML = `<img src="${iconSrc}"/>`
	} else if (iconAfterSrc != null) {
		button.innerHTML = `${button.innerHTML}<img src="${iconAfterSrc}"/>`
	}
}
/**
 * 查找变量名称
 * @param {Object} variableName 变量名称
 */
function findVariable(variableName) {
	let value = window[variableName];

	if (typeof value === 'undefined') {
		try {
			value = eval(variableName);
		} catch (e) {
			throw new Error(`未找到与${variableName}变量相关信息`);
		}
	}
	return value;
}


//下拉菜单
class SiSelect extends HTMLElement {
	static observedAttributes = ['si-model', 'border', 'for', 'si-html', 'value', 'label', 'text', 'placeholder',
		'onchange'
	];

	constructor() {
		super();
		this.placeholder = this.getAttribute('placeholder');
		this.options = [];
		this.isDropdownOpen = false;
		this.currentlySelectedIndex = 0;
		this.selectedValue = null;
		this.siModel = this.getAttribute('si-model');
		this.border = this.getAttribute('border') === 'false' ? false : true;

		this.attachShadow({
			mode: 'open'
		});
	}

	connectedCallback() {
		this.render();
		const selectSelected = this.shadowRoot.querySelector('.select-selected');
		if (selectSelected) {
			selectSelected.addEventListener('click', this.toggleDropdown.bind(this));
		}
		const optionDivs = this.shadowRoot.querySelectorAll('.select-items div');
		if (optionDivs) {
			optionDivs.forEach(div => {
				div.addEventListener('click', () => this.selectOption(div));
			});
		}
		document.addEventListener('click', this.handleDocumentClick.bind(this));

		// 初始化双向绑定
		if (this.siModel) {
			const initialValue = window[this.siModel];
			if (initialValue !== undefined) {
				this.setSelectedValue(initialValue);
			}
		} else {
			// 如果没有 si-model，确保显示 placeholder
			const selectedText = this.shadowRoot.querySelector('.selected-text');
			if (selectedText) {
				selectedText.innerText = this.placeholder;
			}
		}
	}

	disconnectedCallback() {
		document.removeEventListener('click', this.handleDocumentClick.bind(this));
	}

	render() {
		const style = document.createElement('style');
		style.textContent = `
            .select-container {
                position: relative;
                display: inline-block;
                font-size: 14px;
                width: 100%;
            }

            .select-selected {
                background-color: #fff;
                border: ${this.border ? '1px solid #dcdfe6' : 'none'};
                padding: 5px 10px;
                cursor: pointer;
                border-radius: 3px;
                color: #606266;
                padding-right: 30px;
                transition: border-color 0.3s, box-shadow 0.3s;
                position: relative;
                z-index: 3;
                height: 18px;
            }

            .select-arrow {
                position: absolute;
                right: 10px;
                top: 50.25%;
                transform: translateY(-50%);
                border-width: 5px;
                border-style: solid;
                border-color: #dcdfe6 transparent transparent transparent;
                transition: border-color 0.3s, transform 0.3s ease;
            }

            .rotate {
                transform: translateY(-50%) rotate(180deg);
            }

            .select-items {
                display: none;
                background-color: #fff;
                border: ${this.border ? '1px solid #dcdfe6' : 'none'};
                margin: auto;
                color: #606266;
                position: absolute;
                z-index: 4;
                width: 99%;
                border-bottom-right-radius: 4px;
                border-bottom-left-radius: 4px;
            }

            .select-items div {
                padding: 10px;
                cursor: pointer;
            }

            .select-items div:hover {
                background-color: #F2F2F2;
            }
        `;

		const selectContainer = document.createElement('div');
		selectContainer.className = 'select-container';

		const selectSelected = document.createElement('div');
		selectSelected.className = 'select-selected';
		//selectSelected.textContent = this.selectedValue !== null ? this.selectedValue : this.placeholder;

		const selectedText = document.createElement('a');
		selectedText.className = 'selected-text';
		selectedText.innerText = this.selectedValue !== null ? this.selectedValue : this.placeholder;
		selectSelected.appendChild(selectedText);

		const selectArrow = document.createElement('div');
		selectArrow.className = 'select-arrow';
		selectSelected.appendChild(selectArrow);

		const selectItems = document.createElement('div');
		selectItems.className = 'select-items';

		const isFor = this.getAttribute("for");
		const isHtml = this.getAttribute("si-html") === "true";
		const keyValueName = this.getAttribute("value");
		const keyLabelName = this.getAttribute("label");
		const keyTextName = this.getAttribute("text");

		if (isFor) {
			const arrJson = findVariable(isFor);
			arrJson.forEach((jsonData, index) => {
				const optionDiv = document.createElement('div');
				if (isHtml) {
					optionDiv.innerHTML = jsonData[keyLabelName];
				} else {
					optionDiv.innerText = jsonData[keyLabelName];
				}
				if (keyTextName) {
					const hiddenText =
						`<si-text position="right" style="float: right;font-size: 12.5px;margin-top: 5px;">${jsonData[keyTextName]}</si-text>`;
					optionDiv.innerHTML += hiddenText;
				}
				optionDiv.dataset.value = jsonData[keyValueName];
				optionDiv.dataset.index = index;
				selectItems.appendChild(optionDiv);
			});
		} else {
			this.querySelectorAll('si-option').forEach((option, index) => {
				const optionDiv = document.createElement('div');
				if (isHtml) {
					optionDiv.innerHTML = option.innerHTML;
				} else {
					optionDiv.innerText = option.innerText;
				}
				const hiddenText = option.querySelector("si-text");
				if (hiddenText) {
					hiddenText.setAttribute('style',
						`float:${hiddenText.getAttribute("position")};font-size: 12.5px;margin-top: 5px;`
					);
				}
				optionDiv.dataset.value = option.getAttribute('value');
				optionDiv.dataset.index = index;
				selectItems.appendChild(optionDiv);
			});
		}

		selectContainer.appendChild(selectSelected);
		selectContainer.appendChild(selectItems);

		this.shadowRoot.appendChild(style);
		this.shadowRoot.appendChild(selectContainer);
	}

	toggleDropdown() {
		const selectItems = this.shadowRoot.querySelector('.select-items');
		const selectArrow = this.shadowRoot.querySelector('.select-arrow');
		this.isDropdownOpen = !this.isDropdownOpen;

		selectItems.style.display = this.isDropdownOpen ? 'block' : 'none';
		const borderColor = this.isDropdownOpen ? '#606266' : '#dcdfe6';
		const selectSelected = this.shadowRoot.querySelector('.select-selected');

		if (selectSelected) {
			selectSelected.style.borderColor = borderColor;
			selectSelected.style.boxShadow = this.isDropdownOpen && this.border ? '0 2px 5px rgba(0, 0, 0, 0.2)' :
				'none';
		}
		if (selectArrow) {
			selectArrow.style.borderColor = `${borderColor} transparent transparent transparent`;
			if (this.isDropdownOpen) {
				selectArrow.classList.add('rotate');
			} else {
				selectArrow.classList.remove('rotate');
			}
		}
	}

	selectOption(div) {
		this.selectedValue = div.dataset.value;
		this.currentlySelectedIndex = div.dataset.index;
		const selectedText = this.shadowRoot.querySelector('.selected-text');
		if (selectedText) {
			// 移除 si-text 标签
			const doc = new DOMParser().parseFromString(div.innerHTML, 'text/html');
			const body = doc.querySelector('body');
			const children = body.childNodes;
			let textContent = '';
			for (let i = 0; i < children.length; i++) {
				if (children[i].nodeName !== 'SI-TEXT') {
					textContent += children[i].outerHTML || children[i].textContent;
				}
			}
			selectedText.innerHTML = textContent;
		}

		// 更新双向绑定
		if (this.siModel) {
			window[this.siModel] = this.selectedValue;
		}

		// 触发 onchange 事件
		const onchange = this.getAttribute('onchange');
		if (onchange && typeof window[onchange] === 'function') {
			window[onchange](this.selectedValue);
		}

		this.toggleDropdown();
	}

	handleDocumentClick(event) {
		if (!this.contains(event.target) && this.isDropdownOpen) {
			this.toggleDropdown();
		}
	}

	// 设置属性的回调
	attributeChangedCallback(name, oldValue, newValue) {
		switch (name) {
			case 'si-model':
				// 如果设置了 si-model 属性，从 window 对象获取值并设置到选择框
				if (newValue) {
					const value = window[newValue];
					if (value !== undefined) {
						this.setSelectedValue(value);
					}
				}
				break;
			case 'border':
				this.updateBorder(newValue);
				break;
		}
	}

	updateBorder(value) {
		this.border = value === 'false' ? false : true;
		const borderStyle = this.border ? '1px solid #dcdfe6' : 'none';
		const selectSelected = this.shadowRoot.querySelector('.select-selected');
		const selectItems = this.shadowRoot.querySelector('.select-items');
		if (selectSelected) {
			selectSelected.style.border = borderStyle;
		}
		if (selectItems) {
			selectItems.style.border = borderStyle;
		}
	}

	setSelectedValue(value) {
		this.selectedValue = value;
		const selectedOption = this.shadowRoot.querySelector(`.select-items div[data-value="${value}"]`);
		if (selectedOption) {
			const selectedText = this.shadowRoot.querySelector('.selected-text');
			if (selectedText) {
				// 移除 si-text 标签
				const doc = new DOMParser().parseFromString(selectedOption.innerHTML, 'text/html');
				const body = doc.querySelector('body');
				const children = body.childNodes;
				let textContent = '';
				for (let i = 0; i < children.length; i++) {
					if (children[i].nodeName !== 'SI-TEXT') {
						textContent += children[i].outerHTML || children[i].textContent;
					}
				}
				selectedText.innerHTML = textContent;
			}
		} else {
			// 如果没有找到匹配的值，显示 placeholder
			const selectedText = this.shadowRoot.querySelector('.selected-text');
			if (selectedText) {
				selectedText.innerText = this.placeholder;

			}
		}
	}
}

class SiOption extends HTMLElement {
	constructor() {
		super();
	}
}
/*分割线*/
class SiHr extends HTMLElement {
	constructor() {
		super();
		this.attachShadow({
			mode: 'open'
		});
	}

	connectedCallback() {
		this.render();
	}

	render() {
		const style = document.createElement('style');
		style.textContent = `
			
            .solid {
                border-top: 1px solid #606266;
                position: relative;
            }
            .dashed {
                border-top: 1px dashed #606266;
                position: relative;
            }
            .text-left {
                position: absolute;
                left: 0;
                top: -10px; /* Adjust based on your design */
                background: #fff;
                padding: 0 5px;
				margin-left: 1%;
            }
            .text-center {
                position: absolute;
                left: 50%;
                transform: translateX(-50%);
                top: -10px; /* Adjust based on your design */
                background: #fff;
                padding: 0 5px;
            }
            .text-right {
                position: absolute;
                right: 0;
                top: -10px; /* Adjust based on your design */
                background: #fff;
                padding: 0 5px;
				margin-right: 1%;
            }
        `;

		const hr = document.createElement('div');
		const styleType = this.getAttribute('style') || 'solid'; // 默认为 solid
		hr.className = styleType;

		// 处理 si-text 子元素
		const siText = this.querySelector('si-text');
		if (siText) {
			const textPosition = siText.getAttribute('position') || 'left';
			siText.className = `text-${textPosition}`;
			hr.appendChild(siText);
		}

		this.shadowRoot.appendChild(style);
		this.shadowRoot.appendChild(hr);
	}
}
/*分割线文本*/
class SiText extends HTMLElement {
	constructor() {
		super();
		this.attachShadow({
			mode: 'open'
		});
	}

	connectedCallback() {
		this.render();
	}

	render() {
		const style = document.createElement('style');
		style.textContent = `
            .si-hr-text {
                display: inline-block;
				color: #606266;
            }
        `;

		const textContent = document.createElement('span');
		textContent.textContent = this.textContent;
		textContent.className = "si-hr-text"

		this.shadowRoot.appendChild(style);
		this.shadowRoot.appendChild(textContent);
	}
}

//展示文本域内容
class SiTextShow extends HTMLElement {
	static observedAttributes = ['title-position'];

	constructor() {
		super();
		const shadow = this.attachShadow({
			mode: 'open'
		});

		const template = document.createElement('template');
		var htmlFragment = `<style>
                :host {
                    display: block;
                    margin: 20px 0;
                    border: 1px solid #ebeef5;
                    border-radius: 8px;
                    background-color: #fff;
                }

                .title {
                    color: #303133;
                    font-size: 16px;
                    font-weight: 500;
                    padding: 0 10px;
					height: 35px;
                }

                .content {
                    background-color: #f5f5f5;
                    padding: 10px;
                    border-top: 1px solid #ebeef5;
					width: -webkit-fill-available;
                }

                .left {
                    display: flex;
                    align-items: center;
                }

                .bottom {
                    display: flex;
                    flex-direction: column;
                }

                .right {
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;
                }
            </style>`
		if (this.getAttribute('title-position') === "right" || this.getAttribute('title-position') === "bottom") {
			htmlFragment += `
		    <div class="container">
		        <div class="content">
		            <slot></slot>
		        </div>
				<div class="title"><slot name="title" style="display: inline-block;width: max-content;line-height: 35px;"></slot></div>
		    </div>
		`
		} else {
			htmlFragment += `
			    <div class="container">
			        <div class="title"><slot name="title" style="display: inline-block;width: max-content;line-height: 35px;"></slot></div>
			        <div class="content">
			            <slot></slot>
			        </div>
			    </div>
			`
		}

		template.innerHTML = htmlFragment;

		shadow.appendChild(template.content.cloneNode(true));
		this.container = shadow.querySelector('.container');
	}

	attributeChangedCallback(name) {
		if (name === 'title-position') {
			this.container.className = this.getAttribute('title-position');
		}
	}
}
//文本框
class SiInput extends HTMLElement {
	static observedAttributes = ['si-model', 'placeholder', 'verify', 'border', 'disabled', 'size', 'customize-verify',
		'contain-border-color'
	];

	constructor() {
		super();
		this.attachShadow({
			mode: 'open'
		});

		// 创建输入框和验证信息元素
		this.input = document.createElement('input');
		this.verifyInfo = document.createElement('div');

		this.leftSlot = document.createElement('div');
		this.leftSlot.className = 'left-slot';
		this.rightSlot = document.createElement('div');
		this.rightSlot.className = 'right-slot';

		// 设置默认样式
		const style = document.createElement('style');
		style.textContent = `
            .input-container {
                display: flex;
                flex-direction: column;
                width: 100%;
            }

            .input-wrapper {
                display: flex;
                align-items: center;
                border: 1px solid transparent;
                border-radius: 4px;
                transition: all 0.3s ease;ss
                height: max-content;
                margin: 5px;
            }

            input {
                flex: 1;
                border: 1px solid #ddd;
                border-radius: 4px 0 0 4px;
                font-size: 14px;
                padding: 10px;
                transition: all 0.3s ease;
            }

			.left-slot {
                padding: 0 10px;
                font-size: 14px;
                color: #757575;
                background-color: #fff;
                border: 1px solid #ddd;
                border-right: none;
                border-radius: 4px 0 0 4px;
                white-space: nowrap;
                display: none;
                height: 100%;
                display: flex;
                align-items: center;
                transition: all 0.3s ease;
				padding: 3.5px 0px;
            }

            .right-slot {
                padding: 0 10px;
                font-size: 14px;
                color: #757575;
                background-color: #fff;
                border: 1px solid #ddd;
                border-left: none;
                border-radius: 0 4px 4px 0;
                white-space: nowrap;
                display: none;
                height: 100%;
                display: flex;
                align-items: center;
                transition: all 0.3s ease;
				padding: 3.5px 0px;
            }

            input:focus {
                outline: none;
                border-color: #409EFF;
                box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
            }

            input:disabled {
                background-color: #f5f5f5;
                border-color: #ddd;
                cursor: not-allowed;
            }

            input.no-border {
                border: none;
                border-bottom: 1px solid #ddd;
                border-radius: 0;
            }

            input.no-border:focus {
                border-bottom-color: #409EFF;
            }

            .verify-info {
                margin-top: 6px;
                font-size: 12px;
                height: 16px;
                color: transparent;
            }

            .verify-success {
                color: #67C23A;
            }

            .verify-error {
                color: #F56C6C;
            }

            /* 大尺寸 */
            input.size-large {
                padding: 12px;
                font-size: 16px;
            }

            /* 中尺寸（默认） */
            input.size-medium {
                padding: 10px;
                font-size: 14px;
            }

            /* 小尺寸 */
            input.size-small {
                padding: 8px;
                font-size: 12px;
            }
        `;

		// 创建容器并添加元素
		this.container = document.createElement('div');
		this.container.className = 'input-container';

		this.inputWrapper = document.createElement('div');
		this.inputWrapper.className = 'input-wrapper';
		this.inputWrapper.appendChild(this.leftSlot);
		this.inputWrapper.appendChild(this.input);
		this.inputWrapper.appendChild(this.rightSlot);

		this.container.appendChild(this.inputWrapper);
		this.container.appendChild(this.verifyInfo);
		this.container.appendChild(style);

		this.shadowRoot.appendChild(this.container);

		// 初始化事件监听
		this.setupEventListeners();

		// 插入插槽内容
		const leftSlot = document.createElement('slot');
		leftSlot.name = 'left';
		this.leftSlot.appendChild(leftSlot);

		// 插入插槽内容
		const rightSlot = document.createElement('slot');
		rightSlot.name = 'right';
		this.rightSlot.appendChild(rightSlot);

		// 检查是否有右侧插槽内容
		this.updateRightSlotVisibility();
	}

	setupEventListeners() {
		// 输入事件监听
		this.input.addEventListener('input', () => {
			this.updateSiModel();
			this.customizeVerify();
			this.verify();
		});

		// 失去焦点事件监听
		this.input.addEventListener('blur', () => {
			this.verify();
			this.handleBlur();
			this.handleNumberType();
			this.formatValue();
		});

		// 焦点事件监听
		this.input.addEventListener('focus', () => {
			this.handleFocus();
		});
	}

	handleFocus() {
		const containBorderColor = this.getAttribute('contain-border-color');
		if (containBorderColor === 'false') {
			this.inputWrapper.style.borderColor = '#409EFF';
			this.input.style.borderRightColor = '#409EFF';
			this.input.style.borderLeftColor = 'transparent';
			this.input.style.borderTopColor = 'transparent';
			this.input.style.borderBottomColor = 'transparent';
			this.rightSlot.style.borderColor = 'transparent';
		} else {
			this.input.style.borderColor = '#409EFF';
			this.inputWrapper.style.borderColor = 'transparent';
		}
	}

	handleBlur() {
		const containBorderColor = this.getAttribute('contain-border-color');
		if (containBorderColor === 'false') {
			this.inputWrapper.style.borderColor = 'transparent';
			this.input.style.borderColor = '#ddd';
			this.rightSlot.style.borderColor = '#ddd';
		} else {
			this.input.style.borderColor = '#ddd';
			this.inputWrapper.style.borderColor = 'transparent';
		}
	}

	handleNumberType() {
		if (this.getAttribute('type') === 'number') {
			this.input.value = this.input.value.replace(/[^0-9]/g, '');
			console.log(this.input.value);
		}
	}

	verify() {
		const verifyAttr = this.getAttribute('verify');
		if (!verifyAttr) return;

		try {
			// 尝试通过变量名获取验证规则
			const verifyRules = findVariable(verifyAttr);
			if (verifyRules instanceof Array) {
				this.validate(verifyRules);
			} else {
				console.error('验证规则应为数组类型');
			}
		} catch (e) {
			console.error('获取验证规则错误:', e);
		}
	}

	validate(rules) {
		const value = this.input.value.trim();
		let isValid = true;
		let message = '';

		// 验证规则
		for (const rule of rules) {
			if (rule.must !== undefined && rule.must === true && value === '') {
				isValid = false;
				message = rule.message || '此项为必填项';
				break;
			}

			if (rule.min !== undefined && value.length < rule.min) {
				isValid = false;
				message = rule.message || `请输入至少 ${rule.min} 个字符`;
				break;
			}

			if (rule.max !== undefined && value.length > rule.max) {
				isValid = false;
				message = rule.message || `请输入最多 ${rule.max} 个字符`;
				break;
			}

			if (rule.regular !== undefined && !(new RegExp(rule.regular).test(value))) {
				isValid = false;
				message = rule.message || '输入格式不正确';
				break;
			}
		}

		// 更新验证信息
		this.updateVerifyInfo(isValid, message);
	}

	updateVerifyInfo(isValid, message) {
		if (isValid) {
			this.verifyInfo.className = 'verify-info verify-success';
			this.verifyInfo.textContent = '';
		} else {
			this.verifyInfo.className = 'verify-info verify-error';
			this.verifyInfo.textContent = message;
		}
	}

	updateSiModel() {
		const siModel = this.getAttribute('si-model');
		if (siModel) {
			// 更新绑定的变量
			const value = this.input.value;
			window[siModel] = value;
		}
	}

	customizeVerify() {
		const customizeVerifyAttr = this.getAttribute('customize-verify');
		if (customizeVerifyAttr) {
			try {
				// 获取自定义验证函数
				const customizeVerifyFunc = findVariable(customizeVerifyAttr);
				if (typeof customizeVerifyFunc === 'function') {
					// 执行自定义验证函数
					customizeVerifyFunc(this.input.value);

				}
			} catch (e) {
				console.error('自定义验证函数错误:', e);
			}
		}
	}

	// 设置属性的回调
	attributeChangedCallback(name, oldValue, newValue) {
		switch (name) {
			case 'si-model':
				// 如果设置了 si-model 属性，从 window 对象获取值并设置到输入框
				if (newValue) {
					const value = findVariable(newValue);
					if (value !== undefined) {
						this.input.value = value;
					}
				}
				break;
			case 'placeholder':
				this.input.placeholder = newValue;
				break;
			case 'verify':
				this.verify();
				break;
			case 'border':
				this.updateBorder(newValue);
				break;
			case 'disabled':
				this.updateDisabled(newValue);
				break;
			case 'size':
				this.updateSize(newValue);
				break;
			case 'customize-verify':
				this.customizeVerify();
				break;
			case 'contain-border-color':
				this.updateContainBorderColor(newValue);
				break;
			case 'type':
				this.input.type = newValue;
				if (newValue === 'password') {
					this.addPasswordToggle();
				}
				break;
			case 'format':
				this.format = newValue;
				break;
		}
	}

	updateBorder(value) {
		if (value === 'false') {
			this.input.classList.add('no-border');
			this.rightSlot.style.borderLeft = 'none';
		} else {
			this.input.classList.remove('no-border');
			this.rightSlot.style.borderLeft = '1px solid #ddd';
		}
	}

	updateDisabled(value) {
		if (value !== null) {
			this.input.disabled = true;
			this.input.style.cursor = 'not-allowed';
		} else {
			this.input.disabled = false;
			this.input.style.cursor = 'auto';
		}
	}

	updateSize(value) {
		// 移除所有 size 类
		this.input.classList.remove('size-large', 'size-medium', 'size-small');

		// 添加对应 size 类
		switch (value) {
			case 'large':
				this.input.classList.add('size-large');
				break;
			case 'small':
				this.input.classList.add('size-small');
				break;
			default:
				this.input.classList.add('size-medium');
				break;
		}
	}

	updateContainBorderColor(value) {
		if (value === 'false') {
			// 当 contain-border-color 为 false 时，焦点状态下 input-wrapper 变色
			this.inputWrapper.style.borderColor = 'transparent';
		}
	}

	// 获取组件的值
	get value() {
		return this.input.value;
	}

	// 设置组件的值
	set value(value) {
		this.input.value = value;
		this.setAttribute('si-model', value);
	}

	// 检查是否有右侧插槽内容
	updateRightSlotVisibility() {
		const rightSlot = this.shadowRoot.querySelector('slot[name="right"]');
		const leftSlot = this.shadowRoot.querySelector('slot[name="left"]');

		if (rightSlot && rightSlot.assignedNodes().length > 0) {
			this.rightSlot.style.display = 'flex';

			for (var i = 0; i < rightSlot.assignedNodes().length; i++) {
				rightSlot.assignedNodes()[i].style.height = "29px"
			}

			// 判断是否需要取消右侧边框
			if (rightSlot.assignedNodes()[0] !== undefined && rightSlot.assignedNodes()[0].getAttribute('border') ==
				"false") {
				this.input.style.borderRight = 'none';
				this.rightSlot.style.borderLeft = 'none';
			}
		} else {
			this.rightSlot.style.display = 'none';
		}

		if (leftSlot && leftSlot.assignedNodes().length > 0) {
			this.leftSlot.style.display = 'flex';

			for (var i = 0; i < leftSlot.assignedNodes().length; i++) {
				leftSlot.assignedNodes()[i].style.height = "29px"
			}

			// 判断是否需要取消右侧边框
			if (leftSlot.assignedNodes()[0] !== undefined && leftSlot.assignedNodes()[0].getAttribute('border') ==
				"false") {
				this.input.style.borderLeft = 'none';
				this.leftSlot.style.borderRight = 'none';
			}
		} else {
			this.leftSlot.style.display = 'none';
		}
	}
	// 格式化输入值
	formatValue() {
		const format = this.getAttribute('format');
		if (format) {
			try {
				// 获取格式化函数
				const formatFunc = findVariable(format);
				if (typeof formatFunc === 'function') {
					// 执行格式化函数
					const formattedValue = formatFunc(this.input.value);
					this.input.value = formattedValue;
				}
			} catch (e) {
				console.error('格式化函数错误:', e);
			}
		}
	}

	// 添加密码可见性切换功能
	addPasswordToggle() {
		const toggle = document.createElement('span');
		toggle.className = 'password-toggle';
		toggle.textContent = '👁';
		toggle.style.cursor = 'pointer';
		toggle.style.marginLeft = '5px';

		toggle.addEventListener('click', () => {
			if (this.input.type === 'password') {
				this.input.type = 'text';
				toggle.textContent = '👁️';
			} else {
				this.input.type = 'password';
				toggle.textContent = '👁';
			}
		});

		this.rightSlot.appendChild(toggle);
		this.rightSlot.style.display = 'flex';
	}
}

//单选组
class SiRadioGroup extends HTMLElement {
	static observedAttributes = ['si-model', 'disabled', 'name'];

	constructor() {
		super();
		this.attachShadow({
			mode: 'open'
		});

		// 创建容器元素
		this.container = document.createElement('div');
		this.container.className = 'radio-group-container';

		// 创建样式元素
		const style = document.createElement('style');
		style.textContent = `
      .radio-group-container {
        display: flex;
        flex-direction: column;
        width: 100%;
      }

      .radio-group-wrapper {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin: 5px;
      }

      .radio-group-wrapper.horizontal {
        flex-direction: row;
      }

      .radio-group-wrapper.vertical {
        flex-direction: column;
      }

      .radio-group-wrapper.block {
        flex-direction: column;
      }

      .radio-group-wrapper.inline {
        flex-direction: row;
      }
    `;

		// 创建单选按钮组容器
		this.radioGroupWrapper = document.createElement('div');
		this.radioGroupWrapper.className = 'radio-group-wrapper';

		// 将元素添加到容器中
		this.container.appendChild(this.radioGroupWrapper);
		this.container.appendChild(style);

		// 将容器添加到影子根中
		this.shadowRoot.appendChild(this.container);

		// 初始化属性
		this.name = this.getAttribute('name') || 'radio-group';
		this.disabled = this.hasAttribute('disabled');
		this.layout = this.getAttribute('layout') || 'inline';

		// 初始化事件监听
		this.setupEventListeners();
	}

	setupEventListeners() {
		// 监听子元素的变化
		const observer = new MutationObserver((mutations) => {
			mutations.forEach((mutation) => {
				if (mutation.type === 'childList') {
					this.updateRadios();
				}
			});
		});

		observer.observe(this.radioGroupWrapper, {
			childList: true,
			subtree: true
		});
	}

	updateRadios() {
		const radios = this.querySelectorAll('si-radio');
		radios.forEach((radio, index) => {
			radio.index = index;
			radio.name = this.name;
			radio.disabled = this.disabled;
			radio.layout = this.layout;

			radio.addEventListener('change', (e) => {
				this.handleRadioChange(e);
			});
		});
	}

	handleRadioChange(event) {
		const selectedLabel = event.detail;
		const radios = this.querySelectorAll('si-radio');
		radios.forEach(radio => {
			if (radio.label === selectedLabel) {
				radio.setAttribute('checked', '');
			} else {
				radio.removeAttribute('checked');
			}
		});

		if (this.siModel) {
			// 更新绑定的变量
			const variable = findVariable(this.siModel);
			if (variable) {
				variable.value = selectedLabel;
			}
		}
	}

	get siModel() {
		return this.getAttribute('si-model');
	}

	set siModel(value) {
		this.setAttribute('si-model', value);
	}

	get disabled() {
		return this.hasAttribute('disabled');
	}

	set disabled(value) {
		if (value) {
			this.setAttribute('disabled', '');
		} else {
			this.removeAttribute('disabled');
		}
	}

	get layout() {
		return this.getAttribute('layout') || 'inline';
	}

	set layout(value) {
		this.setAttribute('layout', value);
		this.radioGroupWrapper.className = `radio-group-wrapper ${value}`;
	}

	attributeChangedCallback(name, oldValue, newValue) {
		switch (name) {
			case 'si-model':
				// 如果设置了 si-model 属性，从 window 对象获取值并设置到输入框
				if (newValue) {
					const value = findVariable(newValue);
					if (value !== undefined) {
						const radios = this.querySelectorAll('si-radio');
						radios.forEach(radio => {
							if (radio.label === value) {
								radio.setAttribute('checked', '');
							}
						});
					}
				}
				break;
			case 'disabled':
				this.updateRadios();
				break;
			case 'layout':
				this.radioGroupWrapper.className = `radio-group-wrapper ${newValue}`;
				this.updateRadios();
				break;
		}
	}
}

class SiRadio extends HTMLElement {
	static observedAttributes = ['label', 'value', 'checked', 'disabled', 'name', 'layout', 'color'];

	constructor() {
		super();
		this.attachShadow({
			mode: 'open'
		});

		// 创建单选按钮和标签元素
		this.radioInput = document.createElement('input');
		this.radioLabel = document.createElement('span');

		// 设置默认属性
		this.radioInput.type = 'radio';

		// 创建样式元素
		const style = document.createElement('style');
		style.textContent = `
      .radio-container {
        display: flex;
        align-items: center;
        cursor: pointer;
        margin: 5px 0;
      }

      .radio-input {
        appearance: none;
        width: 18px;
        height: 18px;
        border: 2px solid #ccc;
        border-radius: 50%;
        margin-right: 10px;
        transition: all 0.3s ease;
      }

      .radio-input:checked {
        background-color: #2196F3;
        border-color: #2196F3;
      }

      .radio-input:checked::after {
        content: '';
        position: absolute;
        width: 6px;
        height: 6px;
        background-color: white;
        border-radius: 50%;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }

      .radio-label {
        font-size: 14px;
        color: #333;
        transition: all 0.3s ease;
      }

      .radio-input:hover + .radio-label {
        color: #666;
      }

      .radio-input:checked + .radio-label {
        color: #2196F3;
      }

      .radio-input:disabled + .radio-label {
        color: #999;
        cursor: not-allowed;
      }

      /* 垂直布局 */
      .radio-container.vertical {
        flex-direction: column;
        align-items: flex-start;
        margin-right: 0;
        margin-bottom: 10px;
      }

      .radio-input.vertical {
        margin-right: 0;
        margin-bottom: 5px;
      }

      /* 块级布局 */
      .radio-container.block {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: #fff;
      }

      .radio-input.block {
        margin-right: 10px;
      }

      .radio-container.block:hover {
        border-color: #2196F3;
      }

      .radio-input.block:checked + .radio-label {
        color: #2196F3;
      }

      /* 自定义颜色 */
      .radio-input.custom-color:checked {
        background-color: var(--radio-color, #2196F3);
        border-color: var(--radio-color, #2196F3);
      }

      .radio-input.custom-color:checked + .radio-label {
        color: var(--radio-color, #2196F3);
      }
    `;

		// 创建容器并添加元素
		this.container = document.createElement('div');
		this.container.className = 'radio-container';
		this.container.appendChild(this.radioInput);
		this.container.appendChild(this.radioLabel);
		this.container.appendChild(style);

		// 将容器添加到影子根中
		this.shadowRoot.appendChild(this.container);

		// 初始化事件监听
		this.setupEventListeners();
	}

	setupEventListeners() {
		this.container.addEventListener('click', () => {
			this.clickHandler();
		});
	}

	clickHandler() {
		if (this.disabled) return;

		const radioGroup = this.closest('si-radio-group');
		if (radioGroup) {
			const radios = radioGroup.querySelectorAll('si-radio');
			radios.forEach(radio => {
				radio.radioInput.checked = false;
			});
			this.radioInput.checked = true;
			this.dispatchEvent(new CustomEvent('change', {
				detail: this.label
			}));
		}
	}

	get label() {
		return this.getAttribute('label');
	}

	set label(value) {
		this.setAttribute('label', value);
		this.radioLabel.textContent = value;
	}

	get value() {
		return this.getAttribute('value') || this.label;
	}

	set value(value) {
		this.setAttribute('value', value);
	}

	get checked() {
		return this.hasAttribute('checked');
	}

	set checked(value) {
		if (value) {
			this.setAttribute('checked', '');
			this.radioInput.checked = true;
		} else {
			this.removeAttribute('checked');
			this.radioInput.checked = false;
		}
	}

	get disabled() {
		return this.hasAttribute('disabled');
	}

	set disabled(value) {
		if (value) {
			this.setAttribute('disabled', '');
			this.radioInput.disabled = true;
		} else {
			this.removeAttribute('disabled');
			this.radioInput.disabled = false;
		}
	}

	get name() {
		return this.getAttribute('name') || 'radio';
	}

	set name(value) {
		this.setAttribute('name', value);
		this.radioInput.name = value;
	}

	get layout() {
		return this.getAttribute('layout') || 'inline';
	}

	set layout(value) {
		this.setAttribute('layout', value);
		this.container.className = `radio-container ${value}`;
		this.radioInput.className = `${value}`;
	}

	get color() {
		return this.getAttribute('color');
	}

	set color(value) {
		this.setAttribute('color', value);
		this.radioInput.className = `custom-color`;
		this.shadowRoot.style.setProperty('--radio-color', value);
	}

	attributeChangedCallback(name, oldValue, newValue) {
		switch (name) {
			case 'label':
				this.radioLabel.textContent = newValue;
				break;
			case 'value':
				break;
			case 'checked':
				this.radioInput.checked = newValue !== null;
				break;
			case 'disabled':
				this.radioInput.disabled = newValue !== null;
				break;
			case 'name':
				this.radioInput.name = newValue;
				break;
			case 'layout':
				this.container.className = `radio-container ${newValue}`;
				this.radioInput.className = `${newValue}`;
				break;
			case 'color':
				this.radioInput.className = `custom-color`;
				this.shadowRoot.style.setProperty('--radio-color', newValue);
				break;
		}
	}
}










// 注册自定义元素
customElements.define('si-radio', SiRadio);
customElements.define('si-radio-group', SiRadioGroup);
customElements.define('si-input', SiInput);
customElements.define('si-text-show', SiTextShow);
customElements.define('si-select', SiSelect);
customElements.define('si-option', SiOption);
customElements.define('si-hr', SiHr);
customElements.define('si-text', SiText);